package lt.vu.mif.os.processes;

import java.util.List;

import lt.vu.mif.os.RealMachine;
import lt.vu.mif.os.VirtualMachine;
import lt.vu.mif.os.provider.Constants;

public class JobGovernor implements Process {
	private int state;
	public JobGovernor() {
		state = Constants.IDLE;
	}
	
	public String getName() {
		return "Job Governor";
	}
	
	public int getState() {
		return state;
	}
	
	@Override
	public void setState(int state) {
		this.state = state;
	}
	
	public void work() {
		List<VirtualMachine> list = RealMachine.getAllVm();
                
                for (VirtualMachine vm : list) { //finding running vm and set state to IDLE
                    if (vm.getState() == Constants.RUNNING) {
                        vm.setState(Constants.IDLE);
                        break;
                    }
                }
                
                VirtualMachine askingProc = RealMachine.processor.getFirstFromQueue();
                if (askingProc != null) {
                    RealMachine.setRMP(askingProc.getRmp());
                    askingProc.setState(Constants.RUNNING);
                    RealMachine.rmFrame.updatePTRField(Integer.toString((askingProc.getId()-1)*Constants.vmMemSize));
                    RealMachine.rmFrame.updatePCField(Integer.toString((askingProc.registers.getPc() - (askingProc.getId()-1)*Constants.vmMemSize)));
                    RealMachine.rmFrame.updateTIField("10");
                    askingProc.step();
                    askingProc.setRmp(RealMachine.getRMP());
                }
                
                VirtualMachine askingOutput = RealMachine.console.getFirstFromQueue();
                
                if (askingOutput != null) {
                    askingOutput.setState(Constants.ASKING_FOR_PROCESSOR);
                    RealMachine.processor.addToQueue(askingOutput);
                }
                
                VirtualMachine askingInput = RealMachine.input.getFirstFromQueue();
                if (askingInput != null) {
                    askingInput.setState(Constants.ASKING_FOR_PROCESSOR);
                    RealMachine.processor.addToQueue(askingInput);
                }
		
		for (VirtualMachine vm : list) {
			if (vm.getState() == Constants.IDLE)
                            vm.step();
		}
	}
}
